import {
	login,
	getUserInfo
} from '@/api/user'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'
import {
	sha256
} from '@/utils/sha256.min.js'

const state = {
	token: getToken(),
	account: uni.getStorageSync('account') || '',
	userInfo: uni.getStorageSync('user') || '',
	roles: uni.getStorageSync('roles') || []
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_USER_INFO: (state, userInfo) => {
		state.userInfo = userInfo
		uni.setStorageSync('user', userInfo)
	},
	SET_ACCOUNT: (state, account) => {
		state.account = account
		uni.setStorageSync('account', account)
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles
		uni.setStorageSync('roles', roles)
	}
}

const actions = {
	// user login
	login({ commit }, userInfo) {
		const { name, password } = userInfo

		let param = {
			name: encodeURI(name),
			password: sha256(password + name)
		}
		return new Promise((resolve, reject) => {
			login(param).then(res => {
				if (res.success) {
					const { returnObj } = res
					commit('SET_TOKEN', returnObj.access_token)
					commit('SET_ACCOUNT', returnObj.account)
					setToken(returnObj.access_token)
					resolve()
				} else {
					reject(res)
				}
			}).catch(error => {
				reject(error)
			})
		})
	},

	// get user info
	getInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			getUserInfo({ accountNumber: state.account }).then(response => {
				const { data } = response

				if (!data) {
					reject('验证错误, 请重新登陆。')
				}

				const { roles, personDetailBean } = data

				commit('SET_ROLES', roles)
				commit('SET_USER_INFO', personDetailBean)
				resolve(data)
			}).catch(error => {
				reject(error)
			})
		})
	},

	// user logout
	logout({ commit, state }) {
		commit('SET_TOKEN', '')
		commit('SET_ROLES', [])
		removeToken()
		uni.reLaunch({
			url: '/pages/login/index'
		});
	},

	// remove token
	resetToken({ commit }) {
		return new Promise(resolve => {
			commit('SET_TOKEN', '')
			commit('SET_ROLES', [])
			removeToken()
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
